<template>
  <div>
    <el-upload
        action="#"
        accept="image/*"
        :show-file-list="false"
        :before-remove="beforeRemove"
        :on-remove="handleRemove"
        :http-request="onChangeFile"
        :before-upload="beforeAvatarUpload">
        <div class="scumt">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i class="el-icon-plus avatar-uploader-icon"></i> 
        </div>
      </el-upload>
  </div>
</template>

<script>
import {
  Vue,
  ref,
  toRefs,
  shallowRef,
  reactive,
  watch,
  watchEffect,
  getCurrentInstance,
  computed,
  defineComponent,
  nextTick,
  inject,
  onMounted,
  onUnmounted
} from 'vue'
import { Message,MessageBox } from 'element-ui'
import { generateMixed,fileToBase64 } from '@/utils/index'
import store from '@/store'
export default {
  name:'VabQiniuUpload',
    props: {
    limit:{
       type: Number,
      default: ''
    }
  },
  setup(props, { emit }) {
    watch(() => props, (newVal) => {
      query.imageUrl = newVal;
    })
    const Interface = reactive({
      loadImg(row){
        query.imageUrl = row && row.imgUrl ? row.imgUrl : ''
      },
      handleRemove(file, fileList){},
      beforeRemove(file,fileList){
        return MessageBox.confirm(`确定移除 ${ file.name }？`);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          Message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          Message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      async onChangeFile(file){
        query.imageUrl = await fileToBase64(file.file)
        if(query.imageUrl){
          emit('onOk',file.file)
        }
      },
    })
    const query = reactive({
      imageUrl:''
    })
    return {
      ...toRefs(query),
      ...toRefs(Interface)
    }
  }
}
</script>
<style>
  .scumt{
    display: flex;
    align-items: center;
    grid-gap: 10px;
    gap: 10px;
  }
  .avatar-uploader-icon{
    display: block;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
</style>